@import './math';
@import './hsv-hsl';

$hueStep: 2;
$saturationStep: 16; // 饱和度阶梯，浅色部分
$saturationStep2: 5; // 饱和度阶梯，深色部分
$brightnessStep1: 5; // 亮度阶梯，浅色部分
$brightnessStep2: 15; // 亮度阶梯，深色部分
$lightColorCount: 5; // 浅色数量，主色上
$darkColorCount: 4; // 深色数量，主色下

@function getHue($h, $s, $v, $i, $light) {
  $hue: null;

  @if ($h >= 60  and $h <= 240) {
    $hue: if($light, $h - $hueStep * $i, $h + $hueStep * $i);
  }

  @else {
    $hue: if($light, $h + $hueStep * $i, $h - $hueStep * $i);
  }

  @if ($hue < 0) {
    $hue: $hue + 360;
  }

  @else if ($hue >= 360) {
    $hue: $hue - 360;
  }

  @return $hue;
}

@function getSaturation($h, $s, $v, $i, $light) {
  $saturation: 0;

  // grey color don't change saturation
  @if ($h == 0 and $s == 0) {
    @return $s;
  }

  @if ($light) {
    $saturation: $s  - $saturationStep * $i;
  }

  @else if ($i == $darkColorCount) {
    $saturation: $s  + $saturationStep;
  }

  @else {
    $saturation: $s  + $saturationStep2 * $i;
  }

  // 边界值修正
  @if ($saturation > 100) {
    $saturation: 100;
  }

  // 第一格的 s 限制在 6-10 之间
  @if ($light and $i == $lightColorCount and $saturation > 10) {
    $saturation: 10;
  }

  @if ($saturation < 6) {
    $saturation: 6;
  }

  @return round($saturation);
}

@function getValue($h, $s, $v, $i, $light) {
  @return if($light, $v + $brightnessStep1 * $i, $v - $brightnessStep2 * $i);
}

@function colorPalette($color, $level) {
  $light: $level <= 6;
  $hsv: ch-color-to-hsv($color);

  $i: if($light, $lightColorCount + 1 - $level, $level - $lightColorCount - 1);

  $v: nth($hsv, 3);
  $s: nth($hsv, 2);
  $h: nth($hsv, 1);

  //获取转变后的三个h u v值
  $adjustHue: round(getHue($h, $s, $v, $i, $light));
  $adjustSaturation: getSaturation($h, $s, $v, $i, $light);
  $adjustLight: getValue($h, $s, $v, $i, $light);

  @return ch-hsv-to-color($adjustHue, $adjustSaturation, $adjustLight);
}
